package com.zmn.oms.task.job.xno;

import com.alibaba.fastjson.JSON;
import com.github.ltsopensource.core.domain.Action;
import com.github.ltsopensource.core.domain.Job;
import com.github.ltsopensource.spring.tasktracker.JobRunnerItem;
import com.github.ltsopensource.spring.tasktracker.LTS;
import com.github.ltsopensource.tasktracker.Result;
import com.google.common.collect.Lists;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.manager.lts.interfaces.task.TaskManager;
import com.zmn.manager.mq.constant.MqTopicConsts;
import com.zmn.manager.mq.interfaces.ZmnMQSender;
import com.zmn.oms.business.interfaces.work.OrderWorkListBService;
import com.zmn.oms.common.constant.MessageQueueTagConsts;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.manager.utils.TaskConsts;
import com.zmn.oms.model.dto.work.xno.XnoUnBindDTO;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.base.oms.common.model.es.orderwork.EsOrderWork;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @ClassName OrderXnoUnBind
 * @description: 小号解绑
 * @author: wangyanci
 * @create: 2021-08-02 14:45
 * @Version 1.0
 **/
@Slf4j
@LTS
public class OrderXnoUnBindJob {

    @Resource
    TaskManager taskManager;
    @Autowired
    OrderWorkListBService orderWorkListBService;
    @Autowired
    ZmnMQSender zmnMQSender;

    /**
     * 每天早上1点执行
     */
    // @PostConstruct
    void init() {
        Job job = new Job();
        job.setTaskId(TaskConsts.TASK_ID_WORK_COMPLETE_CANCEL_UNBIND_JOB);
        job.setParam(TaskManager.SHARD_FIELD, TaskConsts.TASK_ID_WORK_COMPLETE_CANCEL_UNBIND_JOB);
        job.setCronExpression("0 0 1 1/1 * ? ");
        job.setReplaceOnExist(true);
        ResponseDTO result = taskManager.submitTask2(job);
        if (!result.isSuccess()) {
            log.error("#oms#workCompleteCancelUnBind# job submit fail...");
        }
    }

    /**
     * 工单完成、取消解绑
     *
     * @param job
     * @return
     */
//    @JobRunnerItem(shardValue = TaskConsts.TASK_ID_WORK_COMPLETE_CANCEL_UNBIND_JOB)
    public Result workCompleteCancelUnBind(Job job) {
        log.info("#order#workCompleteCancelUnBind 执行：{}", job);

        try {
            Date date = DateUtil.getNowDefer(-7);
            String startDate = DateUtil.toString(DateUtil.getDateStart(date));
            String endDate = DateUtil.toString(DateUtil.getDateEnd(date));

            unBindCancelOrderWork(startDate, endDate);
            unBindCompleteOrderWork(startDate, endDate);
        } catch (Exception ex) {
            log.error("#order#workCompleteCancelUnBind 执行：{}", job, ex);
            return new Result(Action.EXECUTE_FAILED, "解绑任务执行失败!");
        }

        return new Result(Action.EXECUTE_SUCCESS, "执行成功了!");
    }

    private void unBindCompleteOrderWork(String startDate, String endDate) {
        OrderWorkQuery query = new OrderWorkQuery();
        query.setCompleteTime(String.format("%s,%s", startDate, endDate));
        query.setWorkTypeList(Lists.newArrayList(OrderConsts.ORDER_TYPE_NEW, OrderConsts.ORDER_TYPE_REWORK));
        Integer completeOrderCount = orderWorkListBService.countOrderWorkByQuery(query);

        // 分页处理
        query.setPageSize(10000);

        // 查询次数
        int size = (completeOrderCount / query.getPageSize()) + 1;
        for (int i = 1; i <= size; i++) {
            query.setPageIndex(i);
            List<EsOrderWork> esOrderWorkList = orderWorkListBService.listPageOrderWorkByQuery(query);
            // 发送消息
            for (EsOrderWork esOrderWork : esOrderWorkList) {
                this.sendMessage(esOrderWork.getOrderId(), esOrderWork.getId());
            }
        }
    }

    private void unBindCancelOrderWork(String startDate, String endDate) {
        OrderWorkQuery query = new OrderWorkQuery();
        query.setCancelTime(String.format("%s,%s", startDate, endDate));
        query.setWorkTypeList(Lists.newArrayList(OrderConsts.ORDER_TYPE_NEW, OrderConsts.ORDER_TYPE_REWORK));
        Integer cancelOrderCount = orderWorkListBService.countOrderWorkByQuery(query);
        // 分页处理
        query.setPageSize(10000);

        // 查询次数
        int size = (cancelOrderCount / query.getPageSize()) + 1;
        for (int i = 1; i <= size; i++) {
            query.setPageIndex(i);
            List<EsOrderWork> esOrderWorkList = orderWorkListBService.listPageOrderWorkByQuery(query);
            // 发送消息
            for (EsOrderWork esOrderWork : esOrderWorkList) {
                this.sendMessage(esOrderWork.getOrderId(), esOrderWork.getId());
            }
        }
    }

    private void sendMessage(Long orderId, Long workId) {
        String key = StringUtil.getRandomsString(32);
        log.debug("com.zmn.oms.task.job.xno.OrderXnoUnBind.sendMessage key={},orderId={},workId={}", key, orderId, workId);
        XnoUnBindDTO xnoUnBindDTO = new XnoUnBindDTO();
        xnoUnBindDTO.setOrderId(orderId);
        xnoUnBindDTO.setWorkId(workId);
        zmnMQSender.send(MqTopicConsts.ZMN_TOPIC_OMS, MessageQueueTagConsts.ORDER_XNO_UNBIND, key, JSON.toJSONString(xnoUnBindDTO));
    }

}